package com.ruoyi.match.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.match.domain.*;
import com.ruoyi.match.mapper.MatchClassMapper;
import com.ruoyi.match.util.HandleUpload;

import com.ruoyi.match.exception.CustomException;
import com.ruoyi.match.exception.CustomExceptionType;
import com.ruoyi.match.mapper.MatchEquipmentMapper;
import com.ruoyi.match.mapper.MatchUserEquipmentMapper;
import com.ruoyi.match.mapper.MatchUserMapper;
import com.ruoyi.match.service.MatchUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WYC
 * @since 2021-03-18
 */
@Service
@Slf4j
public class MatchUserServiceImpl  implements MatchUserService {
    @Autowired
    private HandleUpload handleUpload;
    @Autowired
    private MatchUserMapper matchUserMapper;
    @Autowired
    private MatchEquipmentMapper equipmentMapper;
    @Autowired
    private MatchClassMapper matchClassMapper;
    @Autowired
    private MatchUserEquipmentMapper matchUserEquipmentMapper;
    @Value("${param.fileheader}")
    private String fileheader;


    //发送短信的方法
    public boolean phoneBool(String phone) {
        if (phone == null || phone.isEmpty())
            return false;
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if(!phoneBool(phone)){
            throw new CustomException(CustomExceptionType.UNAUTHORIZED, "手机号是否正确");
        }

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4GKdfSqH1iAUmpnKVVGG", "tviPpHeIeLYK5bLKZdM4LOweM7cwOC");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName","Blog学习网站"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_196642077"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public void addUser(String phone, String password,String yzm, MultipartFile headImg, HttpServletRequest request) {
        MatchUser oldUser= matchUserMapper.findPhone(phone);
        if(oldUser!=null){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该手机已经注册");
        }
        String code= (String) request.getSession().getAttribute("CodePhone");
        if(!yzm.equals(code)){
            throw new CustomException(CustomExceptionType.UNAUTHORIZED, "验证码错误");
        }
        if (headImg == null ) {
            //未获取到文件
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "照片文件不存在");
        }
        String fileUrl = "";
        try {
            fileUrl = handleUpload.uploadFile(headImg);
            log.info("图片地址:"+fileheader+fileUrl);
            MatchUser user=new MatchUser(IdUtils.randomUUID(),phone, Md5Utils.hash(password),fileUrl);
            int i=matchUserMapper.addUser(user);
            if(i<=0){
                throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "注册失败");
            }
        } catch (IOException e) {
            throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "图片文件上传异常"+ e.getMessage());
        }
    }

    @Override
    public void login(String phone, String password) {
        MatchUser oldUser= matchUserMapper.findPhone(phone);
        if(oldUser==null){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该手机号尚未注册");
        }

     if( !oldUser.getPassword().equals(Md5Utils.hash(password))){
         throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "密码错误");
        }
    }

    @Override
    public void update(String phone, String password, String name, MultipartFile headImg, Integer age, Integer sex) {

        if(StringUtils.isEmpty(phone)){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "请输入要更新的用户的电话");
        }
        MatchUser user= matchUserMapper.findPhone(phone);
        if(user==null){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "请检查输入，无该用户");
        }
        user.setPhone(phone);
        if(!StringUtils.isEmpty(password)){
            user.setPassword(Md5Utils.hash(password));
        }
        if(!StringUtils.isEmpty(name)){
            user.setName(name);
        }
        if(!StringUtils.isEmpty(age)){
            user.setAge(age);
        }
        if(!StringUtils.isEmpty(sex)){
            user.setSex(sex);
        }
        if (headImg != null ) {
            //未获取到文件
            //先删除之前文件
            handleUpload.deleteFile(user.getHeadImg());
            String  fileUrl;
            try {
                  fileUrl = handleUpload.uploadFile(headImg);
                log.info("图片地址:"+fileheader+fileUrl);
            } catch (IOException e) {
                throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "图片文件上传异常"+ e.getMessage());
            }
            user.setHeadImg(fileUrl);
        }
        int i=matchUserMapper.update(user);
        if(i<=0){
            throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "更新用户资料失败");
        }
    }

    @Override
    public MatchUserVo findByPhone(String phone) {
        MatchUserVo vo=new MatchUserVo();
        MatchUser user = matchUserMapper.findPhone(phone);
        vo.setUser(user);
        if(user.getIsEquipment()==2){
            MatchEquipment matchEquipment = equipmentMapper.selectMatchEquipmentByUerid(user.getPhone());
            vo.setEquipmentId(matchEquipment.getEquipment());
            vo.setStatus(matchEquipment.getStatus());
        }
        return  vo;
    }

    @Override
    public void bangding(String phone, String equipmentId) {
        MatchUser user = matchUserMapper.findPhone(phone);
        if(user.getIsEquipment()==2){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该账户已经绑定设备");
        }
        MatchEquipment matchEquipment = equipmentMapper.selectMatchEquipmentByEqiment(equipmentId);
        if(!StringUtils.isEmpty(matchEquipment.getUserid())){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该设备已经绑定其他用户");
        }
        MatchUserEquipment matchUserEquipment=new MatchUserEquipment(IdUtils.randomUUID(),phone,equipmentId);
      int x=  matchUserEquipmentMapper.addAbout(matchUserEquipment);
      int y = matchUserMapper.updateStatus(phone,1);
      if(x<=0||y<=0){
          throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "绑定失败");
    }
    }

    @Override
    public void Hlogin(String phone, String password) {
        MatchUser oldUser= matchUserMapper.findHPhone(phone);
        if(oldUser==null){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该账户尚未注册");
        }
        if(oldUser.getAuth()!=1){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该账户权限不够");
        }
        if( !oldUser.getPassword().equals(Md5Utils.hash(password))){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "密码错误");
        }
    }

    @Override
    public void jiechu(String phone) {
        MatchEquipment matchEquipment = equipmentMapper.selectMatchEquipmentByUerid(phone);
        if(matchEquipment==null){
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "该账户尚未绑定设备");
        }
       int x= equipmentMapper.updatejiechu(matchEquipment.getId());
        int y= matchUserMapper.updateStatus(phone,0);
        if(x<=0||y<=0){
            throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "解除失败");
        }
    }

    @Override
    public List<MatchUserVo> selectAll(String classId,String name) {
        List<MatchUser> matchUsers = matchUserMapper.selectAll(classId,name);
        List<MatchUserVo> matchUserVos=new ArrayList<>();
        for (MatchUser user: matchUsers) {
            MatchUserVo vo=new MatchUserVo();
            vo.setUser(user);
            if(!StringUtils.isEmpty(user.getClassId())){
                MatchClass matchClass = matchClassMapper.selectMatchClassById((user.getClassId()));
                vo.setClassName(matchClass.getName());
            }
            if(user.getIsEquipment()==2){
                MatchEquipment matchEquipment = equipmentMapper.selectMatchEquipmentByUerid(user.getPhone());
                vo.setEquipmentId(matchEquipment.getEquipment());
                vo.setStatus(matchEquipment.getStatus());
            }
            matchUserVos.add(vo);
        }
        return matchUserVos;
    }

    @Override
    public int updateBan(String[] userIds, String classId) {
        int j=1;
        for (String userid:userIds) {
          int i=  matchUserMapper.updateBanji(userid,classId);
            j=i*j;
        }
        return j;
    }
}
